package com.example.he.p0313_switch;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;

/**
 * 演示ToggleButton的用法
 *
 */
public class SwitchActivity extends AppCompatActivity {
    //声明xml中定义的组件
    private ToggleButton mToggleButton1, mToggleButton2;
    private TextView tvSound1,tvSound2;
    private Switch switcher;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch);
        initView();
    }
    // 初始化控件方法
    private void initView() {
        mToggleButton1 = (ToggleButton) findViewById(R.id.tglSound1); // 获取到控件
        tvSound1 = (TextView) findViewById(R.id.tvSound1);
        // 注册监听器，添加监听事件
        mToggleButton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if (isChecked) {
                    tvSound1.setText("已开启");
                } else {
                    tvSound1.setText("已关闭");
                }

            }
        });

        mToggleButton2 = (ToggleButton) findViewById(R.id.tglSound2); // 获取到控件
        tvSound2 = (TextView) findViewById(R.id.tvSound2);
        // 注册监听器，添加监听事件
        mToggleButton2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if (isChecked) {
                    tvSound2.setText("已开启");
                } else {
                    tvSound2.setText("已关闭");
                }

            }
        });

        //初始化组件
        switcher = (Switch) findViewById(R.id.switcher);
        final LinearLayout test = (LinearLayout) findViewById(R.id.test);
        //为switch组件添加事件监听器
        switcher.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton button,
                                         boolean isChecked) {
                if (isChecked) {
                    // 设置LinearLayout垂直布局
                    test.setOrientation(LinearLayout.VERTICAL);
                    switcher.setChecked(true);
                } else {
                    // 设置LinearLayout水平布局
                    test.setOrientation(LinearLayout.HORIZONTAL);
                    switcher.setChecked(false);
                }
            }
        });

    }

}